package com.tianxia120.website.admin.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @createTime: 2018/9/26 17:50
 * @author: HingLo
 * @description: 菜单管理的服务层
 */
public class MenuService {
    /**
     * 菜单缓存名称
     */
    private final static String CACHE_NAME = "menu";

    /**
     * 请求的菜单列表
     *
     * @return 返回结果
     */
    public List<Record> listService() {
        // 先从菜单中取值
        List<Record> list = CacheKit.get(CACHE_NAME, "list");
        // 如果没有就从数据库中查询
        if (list == null || list.isEmpty()) {
            String sql = Db.getSql("website.menu-list");
            list = createTreeMenu(Db.find(sql));
            if (list != null && !list.isEmpty()) {
                CacheKit.put(CACHE_NAME, "list", list);
            }
        }
        return list;
    }

    /**
     * 菜单递归遍历
     *
     * @param cowList 原始全部的菜单
     * @return 返回结果
     */
    private List<Record> createTreeMenu(List<Record> cowList) {
        CopyOnWriteArrayList<Record> list = new CopyOnWriteArrayList<>(cowList);
        // 定义父ID的字段名称
        String fid = "fid";
        List<Record> resMenu = new ArrayList<>();
        // 遍历所有的一级菜单
        list.forEach(action -> {
            if (action.getInt(fid) == 0) {
                action.remove(fid);
                resMenu.add(action);
                list.remove(action);
            }
        });
        for (Record menu : resMenu) {
            menu.set("child", getChild(menu.getInt("id"), list, fid));
        }
        return resMenu;
    }

    /**
     * 子菜单递归
     *
     * @param id       id
     * @param rootMenu 菜单目录
     * @return 递归好的菜单
     */
    private List<Record> getChild(Integer id, CopyOnWriteArrayList<Record> rootMenu, String fid) {
        // 子菜单
        List<Record> childList = new ArrayList<>();
        rootMenu.forEach(menu -> {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getInt(fid).equals(id)) {
                menu.remove(fid);
                childList.add(menu);
                rootMenu.remove(menu);
            }
        });
        // 把子菜单的子菜单再循环一遍
        childList.forEach(menu -> menu.set("child", getChild(menu.getInt(fid), rootMenu, fid)));
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
